package com.auth.manage.user.domain.service;

import com.alicp.jetcache.Cache;
import com.auth.manage.user.domain.entity.User;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class UserCacheDelayDeleteService {
    // ThreadFactoryBuilder是guava的类，虽然用JDK的ThreadFactory也可以定义线程名字，但是ThreadFactoryBuilder内部帮我们封装好了，可以更简洁地设置
    private ThreadFactory userCacheDelayProcessFactory = new ThreadFactoryBuilder().setNameFormat("user-cache-delay-delete-pool-%d").build();

    // ScheduledExecutorService使用的DelayedWorkQueue是无界的，最大线程数为Integer.MAX_VALUE，有OOM风险
    // DelayedWorkQueue用于实现延迟任务和定时任务
    private ScheduledExecutorService scheduler = new ScheduledThreadPoolExecutor(10, userCacheDelayProcessFactory);

    public void delayedCacheDelete(Cache userCache, User user){
        scheduler.schedule(()->{
            boolean flag = userCache.remove(user.getId().toString());
            log.info("用户缓存被移除，key = {}，result = {}",user.getId(), flag);
        },2, TimeUnit.SECONDS);
    }






}
